<?php 
namespace app\common\service;

use think\Db;
/**
 * 奖励
 */
class User{


	//调整用户级别 用户激活机器人 触发
	static  function setLevel($user_ids){
		$rows = Db::name('user')->where(['id'=>['in',$user_ids]])->select()->toArray();
		if(empty($rows)) return 0;
		try {
			$levels = model('UserLevel')->getAll();
			foreach ($rows as $key => $value) {
				$old_level = $value['level'];
				$new_level = self::calLevel($value['invitation_count'],$value['group_num'],$levels);
				if($new_level==$value['level']) continue;
				//计算此级别对上级的限制
				if($new_level>1){
					$level = get_one_by_item($levels,'level',$new_level);
					if($level['previous_level_num']>0){  //人数不够
						if(Db::name('user')->where(['pid'=>$value['id'],'level'=>$new_level-1])->count()<$level['previous_level_num'] ){
							$new_level = $old_level;
						}
					}
				}
				Db::name('user')->where('id',$value['id'])->update(['level'=>$new_level]);
			}
			return 1;
		} catch (Exception $e) {
			return 0;
		}
	}



	//计算用户级别
	static function calLevel($invite_num,$group_num,$levels){
		if(empty($levels)) return 0;
		for($i=0;$i<count($levels);$i++){
   			if($invite_num>=$levels[$i]['invite_num'] && $group_num>=$levels[$i]['group_num']){
   				return $levels[$i]['level'];
   			}
   		}
		return 0;
	}

}